<template>
    <div class="button">
        <el-upload ref="uploadRef" :limit="1" :auto-upload="false" :show-file-list="false" :accept="['.geojson','.json']" :on-change="handleFileChange" :before-upload="beforeUpload">
            <el-button type="warning">
                上传
            </el-button>
        </el-upload>
    </div>
</template>

<script setup>
import { defineEmits, ref } from "vue"
import { ElMessage }        from "element-plus"

const emits     = defineEmits([ "uploadSuccess" ])
const uploadRef = ref(null)

// 验证文件类型
const beforeUpload = (file) => {
    const isGeoJson = file.name.endsWith(".geojson")
    if(!isGeoJson){
        ElMessage.error("请选择.geojson格式的文件")
        return false
    }
    return true
}

// 处理文件选择
const handleFileChange = (file) => {
    // 如果有文件才进行处理
    if(file.raw){
        const reader = new FileReader()

        // 读取文件完成后的回调
        reader.onload = (e) => {
            try{
                // 解析JSON内容
                const content = JSON.parse(e.target.result)
                ElMessage.success("文件读取成功")
                emits("uploadSuccess", content)

                // 清空选择，允许重新选择同一个文件
                if(uploadRef.value){
                    uploadRef.value.clearFiles()
                }
            }catch(error){
                ElMessage.error("文件内容解析失败，请检查是否为有效的GeoJSON格式")
                console.error("GeoJSON解析错误:", error)
            }
        }

        // 读取文件内容
        reader.readAsText(file.raw)
    }
}
</script>

<style lang="scss" scoped>
.button {
    width: 100%;

    :deep(.el-upload) {
        width: 100%;

        .el-button {
            width: 100%;
        }
    }
}
</style>
